# 创建数据
features <- train_data$data_exprs[all_deg_intersect, ] %>%
    t() %>%
    as_tibble(rownames = "sample")
labels <- train_data$group %>% as_tibble(rownames = "sample")
exp_t <- inner_join(features, labels, by = "sample") %>%
    column_to_rownames("sample")
exp_t[is.na(exp_t)] <- 0

set.seed(1110)
x <- as.matrix(exp_t[, 1:(ncol(exp_t) - 1)])
# x <- exp_t
y <- factor(exp_t[, ncol(exp_t)])

# 准备开始RFE
set.seed(0)
control <- rfeControl(functions = caretFuncs, method = "cv", number = 5)
results <- rfe(x,
    y = y,
    sizes = seq(0, ncol(x)),
    rfeControl = control,
    method = "svmRadial",
    allowParallel = T
)
### 输出结果
svm_res <- predictors(results)
svm_res
mkdir(file.path(od, "SVM"))

write_tsv(tibble(svm_res), file = file.path(od, "SVM/svm_res.txt"))
# 绘制结果
pdf(file.path(od, "SVM/svm_res.pdf"), height = 4, width = 4)
plot(results, type = c("g", "o"))
dev.off()



# 如果使用svm构建模型的话
features <- train_data$data_exprs[marker_gene, ] %>%
    t() %>%
    as_tibble(rownames = "sample")

labels <- train_data$group %>% as_tibble(rownames = "sample")

exp_t <- inner_join(features, labels, by = "sample") %>%
    column_to_rownames("sample")
exp_t[is.na(exp_t)] <- 0


library(pROC)
exp_t %<>% mutate(group = ifelse(group == "Normal", 0, 1))
exp_t %<>% select(group, everything())

str_for <- paste0("group ~ ", paste0(colnames(exp_t)[-1], collapse = " + "))
library(e1071)
model1 <- svm(as.formula(str_for),
    data = exp_t, type = "C-classification",
    kernel = "radial"
)

pre_svm <- predict(model1)
obs_p_svm <- data.frame(prob = pre_svm, obs = exp_t$group)
### 输出混淆矩阵
table(exp_t$group, pre_svm, dnn = c("真实值", "预测值"))
### 绘制ROC曲线
library(pROC)
svm_roc <- roc(exp_t$group, as.numeric(pre_svm))
plot(svm_roc,
    print.auc = TRUE, auc.polygon = TRUE, grid = c(0.1, 0.2), grid.col = c("green", "red"),
    max.auc.polygon = TRUE, auc.polygon.col = "skyblue",
    print.thres = TRUE, main = "SVM模型ROC曲线 kernel = radial"
)
